package org.hibernate.test.dao;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.hibernate.test.dto.UserDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Repository("userRepository")
@Transactional(propagation = Propagation.MANDATORY)
public class UserDao implements IDAO<UserDto> {

	@Autowired
	private SessionFactory sessionFactory;

	@Override
	@SuppressWarnings("unchecked")
	public List<UserDto> listAll() {
		return getSession().createCriteria(UserDto.class).list();
	}

	@Override
	public UserDto getById(Long id) {
		return (UserDto) getSession().get(UserDto.class, id);
	}

	@Override
	public UserDto saveOrUpdate(UserDto user) {
		if (user.getId() != 0L) {
			getSession().merge(user);
		} else {
			getSession().save(user);
		}
		return user;
	}

	@Override
	public void delete(UserDto user) {
		getSession().delete(user);

	}

	@Override
	public Integer count() {
		return (Integer) getSession().createCriteria(UserDto.class).setProjection(Projections.rowCount()).uniqueResult();
	}

	public UserDto findUserByNickName(String nick) {
		Criteria cr = getSession().createCriteria(UserDto.class);
		cr.add(Restrictions.eq("nick", nick));
		return (UserDto) cr.uniqueResult();
	}

	private Session getSession() {
		return sessionFactory.getCurrentSession();
	}
}
